package jym.tan.tmdb.method.auth;

import java.net.URL;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import jym.tan.tmdb.TMDB;
import jym.tan.tmdb.bean.AuthenticationRequest;
import jym.tan.tmdb.constant.TMDBConstants;
import jym.tan.tmdb.method.Base;

public class AuthenticationRequestToken extends Base {

	public AuthenticationRequestToken(TMDB tmdb) {
		super(tmdb, TMDBConstants.AUTHENTICATION, TMDBConstants.NEW_TOKEN);
	}

	public AuthenticationRequest getAuthenticationRequest() throws Exception {
		URL authenticationRequestUrl = getUrl();
		AuthenticationRequest authenticationRequest = getJsonObject(authenticationRequestUrl, AuthenticationRequest.class);
		Map<String, List<String>> headerFields = tmdb.getBrowser().getHttpHeaderResponse();
		boolean nothingFound = true;
		for(Map.Entry<String, List<String>> entry : headerFields.entrySet()) {
			if(StringUtils.isNotBlank(entry.getKey()) && entry.getKey().equalsIgnoreCase("Authentication-Callback") && entry.getValue() != null && StringUtils.isNotBlank(entry.getValue().get(0))) {
				nothingFound = false;
				authenticationRequest.setAuthenticationCallback(entry.getValue().get(0));
			}
		}
		if(nothingFound){
			authenticationRequest.setAuthenticationCallback(null);
		}
		return authenticationRequest;
	}
}
